package com.xd.core.finance.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xd.common.constant.SysConstant;
import com.xd.common.exception.XkdException;
import com.xd.common.util.SecurityUtil;
import com.xd.core.company.mapper.CompanyMapper;
import com.xd.core.finance.dto.RechargeRecordQuery;
import com.xd.core.finance.entity.RechargeRecord;
import com.xd.core.finance.mapper.RechargeRecordMapper;
import com.xd.core.finance.service.IRechargeRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Date;

/**
 * <p>
 * 充值记录表 服务实现类
 * </p>
 *
 * @author ZX
 * @since 2025-03-31
 */
@Service
public class RechargeRecordServiceImpl extends ServiceImpl<RechargeRecordMapper, RechargeRecord> implements IRechargeRecordService {

    @Autowired
    private RechargeRecordMapper rechargeRecordMapper;
    @Autowired
    private CompanyMapper companyMapper;

    @Override
    public Page<RechargeRecord> getList(RechargeRecordQuery query) {
        String companyType = SecurityUtil.getLoginUser().getUser().getCompanyType();
        if (!SysConstant.USER_COMPANY_TYPE_ONE.equals(companyType)) {
            Integer companyId = SecurityUtil.getLoginCompanyId();
            query.setCompanyId(companyId);
        }
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        return (Page<RechargeRecord>) rechargeRecordMapper.getList(query);
    }

    @Transactional
    @Override
    public void insertRecharge(RechargeRecord rechargeRecord) {
        Integer companyId = SecurityUtil.getLoginCompanyId();
        if (companyId == 0) {
            rechargeRecord.setType(SysConstant.PAY_ZERO);
            rechargeRecord.setPayType(SysConstant.PAY_STATUS_FOUR);
            rechargeRecord.setTradeStatus("2");
            rechargeRecord.setTradeTime(new Date());
            save(rechargeRecord);
            companyMapper.addBalance(rechargeRecord);
        }
    }

    @Override
    public void refund(RechargeRecord rechargeRecord) {
        Integer companyId = SecurityUtil.getLoginCompanyId();
        if (companyId == 0) {
            BigDecimal bigDecimal = companyMapper.selectBalance(rechargeRecord.getCompanyId());
            if (bigDecimal.compareTo(rechargeRecord.getAmount())>=0){
                rechargeRecord.setType(SysConstant.PAY_ONE);
                rechargeRecord.setPayType(SysConstant.PAY_STATUS_FOUR);
                rechargeRecord.setTradeTime(new Date());
                rechargeRecord.setTradeStatus("2");
                save(rechargeRecord);
                companyMapper.reduceBalance(rechargeRecord);
            }else {
                throw new XkdException("服务费余额小于退款金额");
            }

        }
    }
}
